#include <iostream>
using std::cout;
using std::endl;

class CirQueue {
   public:
    // 构造函数
    CirQueue(int maxSize = 10)
    : _frontIndex(-1)
    , _rearIndex(-1)
    , _maxSize(maxSize)
    , _size(0)
    , _cirQueue(new int[maxSize]()) 
    {
        cout << "调用构造函数创建循环队列" << endl;
    }

    // 判空
    bool empty() { return _size == 0; }

    // 判满
    bool full() { return _size == _maxSize; }

    // 元素入队
    void push(int val) {
        if (full()) {
            cout << "cirQueue is full!" << endl;
            return;
        }
        if (empty()) {
            _cirQueue[0] = val;
            _rearIndex = 0;
            _frontIndex = 0;
        } else {
            _cirQueue[(_rearIndex + 1) % _maxSize] = val;
            _rearIndex = (_rearIndex + 1) % _maxSize;
        }
        ++_size;
    }

    // 元素出队
    void pop() {
        if (empty()) {
            cout << "cirQueue is empty!" << endl;
            return;
        }
        if (_frontIndex == _rearIndex) {
            _rearIndex = -1;
            _frontIndex = -1;
        } else {
            _frontIndex = (_frontIndex + 1) % _maxSize;
        }
        --_size;
    }

    // 获取队头元素
    int front() {
        if (empty()) {
            cout << "cirQueue is empty!" << endl;
            return -1;
        } else {
            return _cirQueue[_frontIndex];
        }
    }

    // 获取队尾元素
    int back() {
        if (empty()) {
            cout << "cirQueue is empty!" << endl;
            return -1;
        } else {
            return _cirQueue[_rearIndex];
        }
    }

    // 析构函数
    ~CirQueue() {
        if (_cirQueue) {
            delete[] _cirQueue;
            _cirQueue = nullptr;
        }
        cout << "调用析构函数" << endl;
    }

   private:
    int _frontIndex;
    int _rearIndex;
    int _maxSize;
    int _size;
    int* _cirQueue;
};

int main(void) {
    CirQueue cq(5);
    cout << "循环队列大小为5" << endl;
    cout << "循环队列是否为空: " << cq.empty() << endl;
    cout << "循环队列是否为满: " << cq.full() << endl;
    cout << "出队" << endl;
    cq.pop();
    cout << "----------" << endl;

    cq.push(1);
    cq.push(2);
    cq.push(3);
    cq.push(4);
    cout << "1, 2, 3, 4入队" << endl;
    cout << "队头: " << cq.front() << endl;
    cout << "队尾: " << cq.back() << endl;
    cq.push(5);
    cout << "5入队" << endl;
    cout << "队头: " << cq.front() << endl;
    cout << "队尾: " << cq.back() << endl;
    cout << "6入队" << endl;
    cq.push(6);
    cout << "----------" << endl;

    cq.pop();
    cq.pop();
    cq.pop();
    cout << "出队三次" << endl;
    cout << "队头: " << cq.front() << endl;
    cout << "队尾: " << cq.back() << endl;
    cq.push(7);
    cq.push(8);
    cout << "7, 8入队" << endl;
    cout << "队头: " << cq.front() << endl;
    cout << "队尾: " << cq.back() << endl;
    cout << "----------" << endl;

    return 0;
}
